﻿//****************************************************************************
// Copyright (c) 2010 All Right Reserved, http://www.sublight.si/
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from
// the use of this software.
//
// The origin of this software must not be misrepresented; you must not claim
// that you wrote the original software. If you use this software in a product,
// an acknowledgment in the product documentation is required.
//
// Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// The source code of the program may be copied and used for educational,
// non-commercial purposes. The source code may be modified if desired,
// to suit the user.
//
// This notice may not be removed or altered from any source distribution.

using System;
using System.IO;
using NConsoler;
using Utility.Video;

namespace SublightCmd
{
    partial class Program
    {
        /// <summary>
        /// SublightCmd help detect
        /// SublightCmd detect title "C:\video.avi" /titleFormat:"{%TITLE%} ({%YEAR%})"
        /// </summary>
        [Action("detects IMDb/Title and writes it to standard output")]
        public static void Detect(
            [Required(Description = "IMDb|Title")]
            string type,
            [Required(Description = "Path to video file")]
            string filePath,
            [Optional("{%TITLE%} ({%YEAR%})", Description = "How title should be formatted. Default: {%TITLE%} ({%YEAR%}). Supported constants: {%TITLE%}, {%YEAR%}, {%IMDB%}, {%SEASON%}, {%EPISODE%}")]
            string titleFormat,
            [Optional("{%TITLE%} ({%YEAR%}), S{%SEASON%:00}E{%EPISODE%:00}", Description = "How title should be formatted for series. Default: {%TITLE%} ({%YEAR%}), S{%SEASON%:00}E{%EPISODE%:00}. Supported constants: {%TITLE%}, {%YEAR%}, {%IMDB%}, {%SEASON%}, {%EPISODE%}")]
            string titleFormatSeries,
            [Optional(false, Description = "Should only error messages be shown")]
            bool showOnlyErrors
            )
        {
            Guid session = Guid.Empty;

            try
            {
                if (!File.Exists(filePath))
                {
                    throw new Exception("File does not exist");
                }

                string res = null;

                if (string.Compare(type, "IMDb", true) == 0)
                {
                    session = Sublight.Lib.Session.Util.LogInAnonymous();
                    res = Sublight.Lib.IMDB.Util.FindImdbByVideo(session, filePath);
                }
                else if (string.Compare(type, "Title", true) == 0)
                {
                    session = Sublight.Lib.Session.Util.LogInAnonymous();
                    var details = Sublight.Lib.IMDB.Util.FindDetailsByVideo(session, filePath);
                    if (details != null)
                    {
                        if (details.Season != null && details.Episode != null)
                        {
                            res = titleFormatSeries;
                        }
                        else
                        {
                            res = titleFormat;
                        }

                        res = res.Replace("%IMDB%", "0");
                        res = res.Replace("%TITLE%", "1");
                        res = res.Replace("%YEAR%", "2");
                        res = res.Replace("%SEASON%", "3");
                        res = res.Replace("%EPISODE%", "4");

                        res = string.Format(res, details.Id, details.Title, details.Year, details.Season, details.Episode);
                    }
                    else
                    {
                        res = null;
                    }
                }
                else
                {
                    throw new Exception(string.Format("Invalid value: '{0}'", type));
                }

                if (string.IsNullOrEmpty(res))
                {
                    if (!showOnlyErrors)
                    {
                        Console.WriteLine("File is not linked (please use Sublight)");
                    }
                }
                else
                {
                    Console.WriteLine(res);
                }
            }
            catch (Exception ex)
            {
                Environment.ExitCode = 1;
                Console.Error.WriteLine(string.Format("Error occured: {0}", ex.Message));
            }
            finally
            {
                if (session != Guid.Empty)
                {
                    try
                    {
                        Sublight.Lib.Session.Util.LogOut(session);
                    }
                    catch
                    {
                    }
                }
            }
        }
    }
}
